﻿using System.Collections.Generic;
using UnityEngine;

public class UIListGridHorizonContainer : UIListContainer
{
    public float CellSpace = 0;
    public float BeginOffset = 0;
    public float EndOffset = 0;
    public int rowNum = 4;

    protected override void setAnchor()
    {
        Scroll.vertical = false;
        Scroll.horizontal = true;

        RtContent.anchorMin = new Vector2(0, 1);
        RtContent.anchorMax = new Vector2(0, 1);
        RtContent.pivot = new Vector2(0, 1);

        foreach (var tmp in mCells)
        {
            tmp.setAnchor(new Vector2(0, 1), new Vector2(0, 1), new Vector2(0, 1));
        }
    }

    public override void display()
    {
        var maskRect = new Rect((RtContent.sizeDelta.x - MaskContent.sizeDelta.x) * (Scroll.horizontalNormalizedPosition), 0, MaskContent.sizeDelta.x, MaskContent.sizeDelta.y);
        foreach (var tmp in mCells)
        {
            tmp.display(maskRect, RtContent);
        }
    }

    public override void setDatas(List<UIListCell> cells)
    {
        base.setDatas(cells);

        // 游标
        var point = Vector2.zero;
        // Content的大小
        var size = Vector2.zero;
        // point = -2f * Vector2.right * cells[0].getSize().x;
        int n = 1;
        for (int i = 0; i < cells.Count; i++, ++n)
        {
            if (i == 0)
                point += Vector2.right * BeginOffset;

            cells[i].setRect(point);

            if (i == cells.Count - 1)
            {
                size += point;
                size += cells[i].getSize();
                size += Vector2.right * EndOffset;
            }
            else
            {
                if (n % rowNum == 0)
                {
                    point += Vector2.right * (cells[i].getSize().x + CellSpace);
                    // point.x = -2f * cells[i].getSize().x;
                    point.y = 0;
                }
                else
                {
                    point += Vector2.up * (cells[i].getSize().y + CellSpace);
                }
            }
        }
        RtContent.sizeDelta = size;
    }

    protected override void moveToIndex(int index)
    {
        index = index - index % rowNum;
        var cellPos = mCells[index].getPos();
        cellPos.x = Mathf.Min(cellPos.x - BeginOffset, Mathf.Max(0, RtContent.sizeDelta.x - MaskContent.sizeDelta.x));
        RtContent.anchoredPosition = new Vector2(-cellPos.x, cellPos.y);
    }
}